package ca.uvic.cs.cogz.mapping.ui;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.TitledBorder;
import javax.swing.filechooser.FileFilter;

import ca.uvic.cs.cogz.mapping.ontology.DataLoaderFacade;
import edu.stanford.smi.protege.util.ApplicationProperties;
import edu.stanford.smi.protege.util.SystemUtilities;

public class OntologyInputFrame extends JFrame {
	private static final long serialVersionUID = 1924839469521247819L;
	
	private static final String OLD_PLASTIC_LAF_NAME = "com.jgoodies.plaf.plastic.PlasticLookAndFeel";
    private static final String NEW_PLASTIC_LAF_NAME = "com.jgoodies.looks.plastic.PlasticLookAndFeel";
	
	private static final String DEFAULT_SOURCE = "/home/seanf/Desktop/shrimpbib.ecore";
	private static final String DEFAULT_TARGET = "/home/seanf/Desktop/VizModels.ecore";
	
	private InputPanel sourceInputPanel;
	private InputPanel targetInputPanel;
	//private InputPanel mappingInputPanel;
	
	public OntologyInputFrame() {
		init();
	}
	
	private void init() {
		setTitle("CogZ Initialization");
		setSize(new Dimension(600, 200));
		setDefaultCloseOperation(DISPOSE_ON_CLOSE);
		setResizable(false);
		setLocationByPlatform(true);
		
		sourceInputPanel = new InputPanel("Source:", DEFAULT_SOURCE);
		targetInputPanel = new InputPanel("Target:", DEFAULT_TARGET);
		//mappingInputPanel = new InputPanel("Mappings (optional):", "");
		
		sourceInputPanel.fileChooser.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				targetInputPanel.fileChooser.setSelectedFile(sourceInputPanel.fileChooser.getSelectedFile());
			}
		});
		
		this.getContentPane().setLayout(new BorderLayout());
		
		JPanel panel = new JPanel();
		panel.setBorder(new TitledBorder("Ontologies to map:"));
		panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
		panel.add(sourceInputPanel);
		panel.add(targetInputPanel);
		//panel.add(mappingInputPanel);
		
		this.getContentPane().add(panel, BorderLayout.CENTER);
		
		JPanel buttonPanel = new JPanel();
		JButton okButton = new JButton("Perform mapping");
		okButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				performMapping();
			}
		});
		JButton cancelButton = new JButton("Cancel");
		cancelButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				dispose();
			}
		});
		buttonPanel.add(okButton);
		buttonPanel.add(cancelButton);
		
		this.getContentPane().add(buttonPanel, BorderLayout.SOUTH);
		
		setVisible(true);
	}
	
	private void performMapping() {
		if(isInputValid()) {
			setVisible(false);
			DataLoaderFacade.getInstance().loadMapping(this, sourceInputPanel.getFilePath(), targetInputPanel.getFilePath());
		}
		else {
			JOptionPane.showMessageDialog(this, "You must supply a valid source and target ontology.");
		}
	}
	
	private boolean isInputValid() {
		return sourceInputPanel.getFilePath().length() > 0 && targetInputPanel.getFilePath().length() > 0
			&& new File(sourceInputPanel.getFilePath()).exists() && new File(targetInputPanel.getFilePath()).exists();
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// set the look and feel to the plastic theme
		String lafName = ApplicationProperties.getLookAndFeelClassName();
        if (lafName.equals(OLD_PLASTIC_LAF_NAME)) {
            lafName = NEW_PLASTIC_LAF_NAME;
            ApplicationProperties.setLookAndFeel(lafName);
        }
        SystemUtilities.setLookAndFeel(lafName);
		
		new OntologyInputFrame();
	}

	class InputPanel extends JPanel {
		private static final long serialVersionUID = -4831688238278578967L;
		
		private JFileChooser fileChooser;
		private JLabel inputLabel;
		private JTextField inputField;
		private JButton browseButton;
		
		public InputPanel(String title, String defaultText) {
			inputLabel = new JLabel(title);
			inputField = new JTextField(defaultText, 35);
			browseButton = new JButton("Browse");
			fileChooser = new JFileChooser();
			ExtensionFileFilter fileFilter = new ExtensionFileFilter("Models/Ontologies (.pprj, .owl, .ecore)", new String[] {"pprj", "ecore", "owl"});
			fileChooser.setFileFilter(fileFilter);
			
			browseButton.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					showFileSelection();
				}
			});
			
			inputLabel.setPreferredSize(new Dimension(115, 25));
			
			add(inputLabel);
			add(inputField);
			add(browseButton);
		}
		
		public String getFilePath() {
			return inputField.getText();
		}
		
		private void showFileSelection() {
			fileChooser.showOpenDialog(this);
			if(fileChooser.getSelectedFile() != null) {
				inputField.setText(fileChooser.getSelectedFile().getAbsolutePath());
			}
		}
	}
	
	class ExtensionFileFilter extends FileFilter {
		String description;

		String extensions[];

		public ExtensionFileFilter(String description, String extension) {
			this(description, new String[] { extension });
		}

		public ExtensionFileFilter(String description, String extensions[]) {
			if (description == null) {
				this.description = extensions[0] + "{ " + extensions.length
						+ "} ";
			} else {
				this.description = description;
			}
			this.extensions = (String[]) extensions.clone();
			toLower(this.extensions);
		}

		private void toLower(String array[]) {
			for (int i = 0, n = array.length; i < n; i++) {
				array[i] = array[i].toLowerCase();
			}
		}

		public String getDescription() {
			return description;
		}

		public boolean accept(File file) {
			if (file.isDirectory()) {
				return true;
			} else {
				String path = file.getAbsolutePath().toLowerCase();
				for (int i = 0, n = extensions.length; i < n; i++) {
					String extension = extensions[i];
					if ((path.endsWith(extension) && (path.charAt(path.length()
							- extension.length() - 1)) == '.')) {
						return true;
					}
				}
			}
			return false;
		}
	}

}
